package com.guns.dome1.session;

import com.guns.dome1.utils.EncryptUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class SessionService {
    private Map<String, Long> sessionMap;
    private Random random = new Random();
    private static int EXPIRE_TIME = 300 * 60 * 1000;

    public SessionService() {
        sessionMap = new HashMap<>();
    }

    /**
     * 建立session，用于返回给用户
     *
     * @return
     */
    public String save() {
        String str = random.nextInt() + "";
        String session = EncryptUtil.md5(str);
        sessionMap.put(session, System.currentTimeMillis());
        return session;
    }

    /**
     * 刷新session有效时间
     *
     * @param session
     * @return
     */
    public String save(String session) {
        sessionMap.put(session, System.currentTimeMillis());
        return session;
    }

    /**
     * 刷新session有效时间
     *
     * @param session
     * @return
     */
    public boolean check(String session) {
        Long time = sessionMap.get(session);
        if (time == null) {
            return false;
        }

        if (System.currentTimeMillis() - time > EXPIRE_TIME) {
            //超时
            return false;
        }
        return true;
    }

    /**
     * 登出时删除此session
     *
     * @param session
     */
    public void remove(String session) {
        sessionMap.remove(session);
    }


}
